/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 11:47:22
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-10 17:08:17
 * @FilePath: \keep_motion_api\models\user\member.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 会员模型
const memberSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  level: {
    type: String,
    default: "bronze"
  },
  expire_date: Date,
  benefits: [String],
  course_discounts: {
    type: Number,
    min: 0,
    max: 100,
    default: 0
  }
});
memberSchema.statics.getMembers = async function (level, expire_date, offset, limit) {
  try {
    const query = {};
    if (level) query.level = level;
    if (expire_date) query.expire_date = { $lte: new Date(expire_date) };
    const aggregationPipeline = [
      // 匹配条件
      { $match: query },
      // 关联用户表，只获取 name 字段
      { $lookup: {
          from: 'users',
          localField: 'user_id',
          foreignField: '_id',
          as: 'userInfo'
        }
      },
      // 展开用户信息数组
      { $unwind: {
          path: '$userInfo',
          preserveNullAndEmptyArrays: true
        }
      },
      // 添加用户名字段（避免嵌套）
      { $addFields: {
          userName: { $ifNull: ['$userInfo.name', '未知用户'] }
        }
      },
      // 移除临时字段
      { $project: {
          userInfo: 0
        }
      },
      // 分页处理
      { $skip: Number(offset || 0) },
      { $limit: Number(limit || 10) }
    ];
    const total = await this.countDocuments(query);
    const rows = await this.aggregate(aggregationPipeline);
    return { rows, total };
  } catch (error) {
    throw error;
  } 
}
memberSchema.statics.createMember = async function (memberData) {
  try {
    const member = new this(memberData);
    return await member.save();
  } catch (error) {
    throw error;
  }
}
memberSchema.statics.updateMember = async function (id, memberData) {
  try {
    return await this.findByIdAndUpdate(id, memberData, { new: true });
  } catch (error) {
    throw error;
  }
}
memberSchema.statics.deleteMember = async function (id) {
  try {
    return await this.findByIdAndDelete(id);
  } catch (error) {
    throw error;
  }
}
module.exports = mongoose.model('Member', memberSchema);
